package com.copera.cn.kaka;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.R.string;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.copera.cn.kaka.picpopupwindow.SelectPicPopupWindow;
import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.Options;
import com.copera.cn.kaka.util.UploadUtil;
import com.copera.cn.kaka.util.Utility;
import com.google.zxing.common.StringUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ShopPhotoActivity extends BaseActivity {
	private ImageView shopphoto, bigphoto;
	// 自定义的弹出框类
	private SelectPicPopupWindow menuWindow;
	private String type;
	private RelativeLayout back;

	private EditText description;

	private File picFile;
	private final int activity_result_camara_with_data = 1006;
	private final int activity_result_cropimage_with_data = 1007;
	private Uri photoUri;
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	private TextView sav;
	private int displayWidth;
	private Bitmap bp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.shop_photo);
		back = (RelativeLayout) findViewById(R.id.back);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;
		type = getIntent().getStringExtra("type");
		description = (EditText) findViewById(R.id.description);
		shopphoto = (ImageView) findViewById(R.id.photo);
		bigphoto = (ImageView) findViewById(R.id.bigphoto);
		sav = (TextView) findViewById(R.id.sav);
		shopphoto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实例化SelectPicPopupWindow
				menuWindow = new SelectPicPopupWindow(ShopPhotoActivity.this,
						itemsOnClick);
				// 显示窗口
				menuWindow.showAtLocation(findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置

			}
		});
		bigphoto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实例化SelectPicPopupWindow
				menuWindow = new SelectPicPopupWindow(ShopPhotoActivity.this,
						itemsOnClick);
				// 显示窗口
				menuWindow.showAtLocation(findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置

			}
		});
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (bp != null) {
					//bp.recycle();
				}
				finish();

			}
		});

		sav.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				boolean bool = true;
				String descriptions = description.getText().toString();
				if (descriptions == null || "".equals(descriptions)) {
					bool = false;
					Toast.makeText(ShopPhotoActivity.this, "请输入活动描述",Toast.LENGTH_SHORT).show();
				} else if (getAppCustomer().getPhotoFile() == null&&bp==null) {
					bool = false;
					Toast.makeText(ShopPhotoActivity.this, "请上传店铺活动宣传图片",
							Toast.LENGTH_SHORT).show();
				}else if (descriptions.length() > 25) {
					bool = false;
					Toast.makeText(ShopPhotoActivity.this, "您输入的活动描述字数超过25个字",Toast.LENGTH_SHORT).show();
				}
				if (bool) {
					if(photo.equals("1")){
						upload(bp);
					}else{
						upload();
					}
					Intent data=new Intent();  
					 data.putExtra("filename", file.getAbsolutePath()); 
					 setResult(120, data); 
					
					finish();
				}
			}
		});

		displayWidth = dm.widthPixels;
		// 强制为竖屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		description.setFocusable(true);
	}

	// 为弹出窗口实现监听类
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();
			Intent intent = null;
			int id = v.getId();
			if (id == R.id.btn_take_photo) {

				intent = new Intent(ShopPhotoActivity.this, PhotoActivity.class);
				intent.putExtra("type", "banner");
				startActivityForResult(intent, 100);
				overridePendingTransition(R.layout.push_left_in,
						R.layout.push_left_out);
			} else if (id == R.id.btn_pick_photo) {
				intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
				getAppCustomer().setSelectType("zm");
			} else {
				// finish();
			}

		}
	};

	ImageLoader imageLoader = ImageLoader.getInstance();
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 40) {
			 photo="1";
			    imageLoader.displayImage("file://"+getAppCustomer().getPhotoFile(), bigphoto, Options.getListOptions());
			    bp = getAppCustomer().getGgimage();
				bigphoto.setVisibility(View.VISIBLE);
				shopphoto.setVisibility(View.GONE);
		} else if (resultCode == Activity.RESULT_OK) {
			doPhoto(requestCode, data);
			photo="2";

		}
		super.onActivityResult(requestCode, resultCode, data);

	}
	private String photo;
	public void upload(Bitmap bitmap) {

		UploadUtil uploadUtil = UploadUtil.getInstance();
		File file = null;

		try {
			
			try {
				file = UploadUtil.saveMyBitmap(bitmap);
				long size = file.length() / 1024;

				System.out.println(size);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (Exception e) {

			e.printStackTrace();
		}
        getAppCustomer().setPhotoFile(null);
		Map<String, String> params = new HashMap<String, String>();
		params.put("shopId",getValue("shopId"));
		params.put("type", type);
		params.put("description", description.getText().toString());
		params.put("flag", "set");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",
				ActionUrls.URL_UPLOAD, params);
		description.setFocusable(true);
		bitmap.recycle();
	}
	private File file;
	public void upload() {

		UploadUtil uploadUtil = UploadUtil.getInstance();
	

		try {
			file = UploadUtil.saveFile(picPath);
			long size = file.length() / 1024;

			System.out.println(size);
		} catch (Exception e) {

			e.printStackTrace();
		}

		Map<String, String> params = new HashMap<String, String>();
		if(getAppCustomer().getShop()==null){
			params.put("shopId", "1");
		}else{
			params.put("shopId", getValue("shopId"));
		}
		
		params.put("type", type);
		params.put("description", description.getText().toString());
		params.put("flag", "set");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",
				ActionUrls.URL_UPLOAD, params);
		description.setFocusable(true);
	}

	private String picPath;

	private void doPhoto(int requestCode, Intent data) {
		if (data != null) {
			if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // 从相册取图片，有些手机有异常情况，请注意
			{
				if (data == null) {
					Toast.makeText(ShopPhotoActivity.this, "选择图片文件出错",
							Toast.LENGTH_LONG).show();
					return;
				}
				photoUri = data.getData();
				if (photoUri == null) {
					Toast.makeText(ShopPhotoActivity.this, "选择图片文件出错",
							Toast.LENGTH_LONG).show();
					return;
				}
			}
			String[] pojo = { MediaStore.Images.Media.DATA };

			// Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
			ContentResolver cr = getContentResolver();
			Cursor cursor = cr.query(photoUri, pojo, null, null, null);
			if (cursor != null) {
				int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
				cursor.moveToFirst();
				picPath = cursor.getString(columnIndex);
				cursor.close();
			}

			if (picPath != null
					&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
							|| picPath.endsWith(".jpg")
							|| picPath.endsWith(".JPG") || picPath
								.endsWith(".jpeg"))) {
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(picPath, opts);
				File f = new File(picPath);
				if(f.length()/1024<100){
					opts.inSampleSize = 1;
				}else{
					opts.inSampleSize = Utility.getinSampleSize(opts);
				}
			
				opts.inJustDecodeBounds = false;
				int jd = Utility.readPictureDegree(picPath);
				bp = BitmapFactory.decodeFile(picPath, opts);
				bp = UploadUtil.rotaingImageView(jd, bp);
				try {

					imageLoader.displayImage("file://"+picPath, bigphoto, Options.getListOptions());
					bigphoto.setVisibility(View.VISIBLE);
					shopphoto.setVisibility(View.GONE);
				} catch (Exception e) {

					e.printStackTrace();
				}

			} else {
				Toast.makeText(ShopPhotoActivity.this, "选择图片文件不正确",
						Toast.LENGTH_LONG).show();
			}
		}

	}

	

	

	public void upload(String picturePath) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(picturePath, opts);

		opts.inSampleSize = 10;
		opts.inJustDecodeBounds = false;

		UploadUtil uploadUtil = UploadUtil.getInstance();
		
		try {
			file = UploadUtil.saveMyBitmap(BitmapFactory.decodeFile(
					picturePath, opts));
		} catch (IOException e) {

			e.printStackTrace();
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("shopId", getValue("shopId"));
		params.put("type", type);
		params.put("description", description.getText().toString());
		params.put("flag", "set");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",
				ActionUrls.URL_UPLOAD, params);
		try {
			Thread.sleep(600);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public Bitmap getPic(String uriPic) {
		URL imageUrl = null;
		Bitmap bitmap = null;
		try {
			imageUrl = new URL(uriPic);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.connect();
			int nRC = conn.getResponseCode();// 得到连接状态
			if (nRC == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);

				is.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
}
